//
//  MCAnalyzedResult.m
//  iMooc
//
//  Created by CoderXSLee on 13/6/3.
//  Copyright © 2013年 李雪松. All rights reserved.
//

#import "MCTip.h"
#import "MCNetworking.h"
#import "MCAnalyzedResult.h"

@implementation MCCommonResult

@synthesize resultCode = _resultCode;
@synthesize resultDesc = _resultDesc;

- (instancetype)init {
    if (self = [super init]) {
        self.resultCode = MC_RESULT_FAILURE;
        self.resultDesc = @"";
    }
    return self;
}

- (instancetype)initWithResultCode:(NSInteger)code desc:(NSString *)desc {
    if (self = [self init]) {
        self.resultCode = code;
        self.resultDesc = desc;
    }
    return self;
}

- (instancetype)initWithResultCode:(NSInteger)code desc:(NSString *)desc request:(NSURLRequest *)request {
    if (self = [self init]) {
        self.resultCode = code;
        self.resultDesc = desc;
        self.request = request;
    }
    return self;
}


#pragma mark - class method
+ (instancetype)resultWithResponse:(id)response request:(NSURLRequest *)request {
    if (response != nil && response != [NSNull null] && [response isKindOfClass:[NSDictionary class]]) {
        NSString *codeKey = [MCNetworking sharedInstance].responseObjectKeys[@"responseCodeKey"];
        NSString *messageKey = [MCNetworking sharedInstance].responseObjectKeys[@"responseMessageKey"];
        MCResultCode code = [[response objectForKey:codeKey] integerValue];
        NSString *desc = [response objectForKey:messageKey];
        return [self resultWithCode:code desc:desc request:request];
    }
    return [self resultWithCode:-1 desc:@"response=nil" request:request];
}

+ (instancetype)resultWithCode:(NSInteger)code desc:(NSString *)desc {
    return [[self alloc] initWithResultCode:code desc:desc];
}

+ (instancetype)resultWithCode:(NSInteger)code desc:(NSString *)desc request:(NSURLRequest *)request {
    return [[self alloc] initWithResultCode:code desc:desc request:request];
}

@end



@implementation MCAnalyzedResult

/**
 *  判断结果码是否面向用户
 *
 *  @return YES-面向用户 NO-内部消化
 */
- (BOOL)isExposedToUser {
    return [self isExposedToUser:self.resultCode];
}

- (BOOL)isExposedToUser:(NSInteger)resultCode {
    BOOL exposedToUser = NO;
    MCResultCodeDigitalRange range = [MCNetworking sharedInstance].codeRange;
    // a ~ b 范围的结果码，需要面向用户
    if (resultCode >= range.startNumber && resultCode <= range.endNumber) {
        exposedToUser = YES;
    }
    return exposedToUser;
}

- (void)show:(NSString *)resultDesc {
    [MCTip showHint:resultDesc];
}

- (void)show {
    [self show:self.resultDesc];
}

@end
